package com.whfc.ms.api.base.service.impl;

import cn.hutool.core.util.URLUtil;
import com.whfc.base.dto.AppDocumentManageDTO;
import com.whfc.base.entity.AppDocumentManage;

import com.whfc.base.service.AppDocumentManageService;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.result.PageVO;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.AssertUtil;
import com.whfc.common.util.RandomUtil;
import com.whfc.entity.dto.warn.OssFileInfoDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysUserService;
import com.whfc.fuum.utils.UserUtils;
import com.whfc.ms.api.base.service.DocumentManageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * (AppDocumentManage)表服务实现类
 *
 * @author makejava
 * @since 2022-07-13 15:31:14
 */
@Service
public class DocumentManageServiceImpl implements DocumentManageService {
    @DubboReference(interfaceClass = AppDocumentManageService.class, version = "1.0.0")
    private AppDocumentManageService appDocumentManageService;
    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;


    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FileHandler fileHandler;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AppDocumentManage queryById(Integer id) {
        return this.appDocumentManageService.queryById(id);
    }


    @Override
    public List<AppDocumentManageDTO> queryAllFolderById(Integer deptId) {
//        List<AppDocumentManage> appDocumentManages = appDocumentManageService.queryByDocType(0);
        return appDocumentManageService.queryByDocType(deptId, 0);
    }

    /**
     * 分页查询文件
     *
     * @return 查询结果
     */
    @Override
    public PageVO<AppDocumentManageDTO> queryPageByFolderId(Integer deptId, Integer folderId, Integer pageNum, Integer pageSize,String name) {
        PageVO<AppDocumentManageDTO> appDocumentManageDTOPageVO = appDocumentManageService.queryPageByDocType(deptId, null, folderId, pageNum, pageSize, name);
        List<AppDocumentManageDTO> list = appDocumentManageDTOPageVO.getList();
        list.forEach(appDocumentManageDTO -> {
            SysUser userById = sysUserService.getUserById(appDocumentManageDTO.getCreateUser());
            SysUser updateUser = sysUserService.getUserById(appDocumentManageDTO.getUpdateUser());
            appDocumentManageDTO.setCreateUserName(userById==null?"":userById.getUsername());
            appDocumentManageDTO.setUpdateUserName(updateUser==null?"":updateUser.getUsername());
        });
        return appDocumentManageDTOPageVO;
    }


    /**
     * 新增数据
     *
     * @param appDocumentManage 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public String addFolder(AppDocumentManage appDocumentManage) {
        try{
            SysUser loginUser = UserUtils.getLoginUser();
            appDocumentManage.setCreateUser(loginUser.getId());
            appDocumentManage.setUpdateUser(loginUser.getId());
            this.appDocumentManageService.insert(appDocumentManage);
        }catch (Exception e)           {
            throw new BizException(ResultEnum.FAILURE.getCode(), "新增失败");
        }


        return "新增成功";
    }

    /**
     * 修改数据
     *
     * @return 实例对象
     */
    @Override
    @Transactional
    public String update(List<AppDocumentManage> appDocumentManages) {
        SysUser loginUser = UserUtils.getLoginUser();
        for (AppDocumentManage appDocumentManage: appDocumentManages) {
            appDocumentManage.setUpdateUser(loginUser.getId());
            int update = this.appDocumentManageService.update(appDocumentManage);
            if(update != 1){
                throw new BizException(ResultEnum.FAILURE.getCode(), "更新失败");
            }
        }
        return "更新成功";
    }


    @Override
    public OssFileInfoDTO uploadFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        String[] split = fileName.split("\\.");
        String contentType =  split[split.length-1];
        String suffix = "";
        if (StringUtils.isNotBlank(fileName) && fileName.contains(".")) {
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        String newName = RandomUtil.getRandomFileName() + suffix;
        InputStream inputStream = file.getInputStream();
        String path = filePathConfig.getFilePath("documentManage/file", newName)
;
        String upload = fileHandler.upload(path, inputStream);
        OssFileInfoDTO data = new OssFileInfoDTO();
        data.setPath(upload);
        data.setSize(size);
        data.setFileType(contentType);
        data.setName(fileName);
        return data;
    }

    @Override
    public Map<String, String> getConfig(String name) {
        String suffix = null;
        if (name != null) {
            suffix = name.substring(name.lastIndexOf("."));
        }
        String path = filePathConfig.getFilePath("documentManage/file");
        String newName = RandomUtil.getRandomFileName() + suffix;
        // 获取配置
        Map<String, String> policy = fileHandler.getPolicy(path);
        policy.put("fileName", newName);
        return policy;
    }

    @Override
    public Map<String, String> getFileUrl(Integer fileId) {
        String suffix = null;

        String path = filePathConfig.getFilePath("documentManage/file");
        Map<String, String> ret = new HashMap<>();
        AppDocumentManage appDocumentManage = appDocumentManageService.queryById(fileId);
        String fileUrl = appDocumentManage.getFileUrl();
        if (fileUrl != null) {
            String[] split = fileUrl.split("\\.");
            suffix=  split[split.length-1];
        }
        Map<String, String> policy = fileHandler.getPolicy(path);
        String host = policy.get("host");
        String key = fileUrl.replace(host.concat("/"), "");
        String s = fileHandler.parsOssUrl(key);
        ret.put("fileUrl",fileUrl.concat("?").concat(s));
        ret.put("suffix",suffix);
        return ret;
    }


    /**
     * 分页查询文件
     *
     * @return 查询结果
     */
    @Override
    public PageVO<AppDocumentManageDTO> queryFilePageByFolderId(Integer deptId, Integer folderId, Integer pageNum, Integer pageSize,String name) {

        if(null == folderId){
            folderId = -1;
        }
        List<AppDocumentManageDTO> appDocumentManageDTOS = appDocumentManageService.queryByDocType(deptId, 0, folderId);
        List<Integer> folderIds = new ArrayList<>();
        appDocumentManageDTOS.forEach(appDocumentManageDTO -> {
            folderIds.addAll(getChildFolderIds(appDocumentManageDTO));
        });
        folderIds.add(folderId);
        PageVO<AppDocumentManageDTO> appDocumentManageDTOPageVO = appDocumentManageService.queryPageByDocType(deptId, 1, folderIds, pageNum, pageSize, name);
        List<AppDocumentManageDTO> list = appDocumentManageDTOPageVO.getList();
        list.forEach(appDocumentManageDTO -> {
            SysUser userById = sysUserService.getUserById(appDocumentManageDTO.getCreateUser());
            SysUser updateUser = sysUserService.getUserById(appDocumentManageDTO.getUpdateUser());
            appDocumentManageDTO.setCreateUserName(userById==null?"":userById.getUsername());
            appDocumentManageDTO.setUpdateUserName(updateUser==null?"":updateUser.getUsername());
        });
        return appDocumentManageDTOPageVO;
    }

    @Override
    public void rename(Integer id, String name) {
        AppDocumentManage data = appDocumentManageService.queryById(id);
        AssertUtil.isTrue(data == null || data.getDelFlag() == 1, "信息不存在");
        String newName = null;
        try {
            newName = URLEncoder.encode(name, "UTF-8");
        } catch (Exception e) {
            AssertUtil.throwsException("文件名称编码失败");
        }
        if (data.getDocType() == 1) {
            String key = URLUtil.getPath(data.getFileUrl()).replaceFirst("/", "");
            fileHandler.rename(key, newName);
        }
        data.setName(name);
        data.setUpdateTime(new Date());
        appDocumentManageService.update(data);
    }

    List<Integer>  getChildFolderIds(AppDocumentManageDTO appDocumentManageDTO){
        List<Integer> folderIds = new ArrayList<>();
        folderIds.add(appDocumentManageDTO.getId());
        List<AppDocumentManageDTO> childFolder = appDocumentManageDTO.getChildFolder();
        childFolder.forEach(c->{
            folderIds.addAll(getChildFolderIds(c));
        });
        return folderIds;
    }
}
